//
//  MainViewController.m
//  We365
//
//  Created by Bui Thien An on 11/27/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "DBManager.h"
#import "Settings.h"
#import "Display.h"
#import "MainViewController.h"
#import "CategoryViewController.h"
#import "SearchViewController.h"
#import "SettingsViewController.h"
#import "AboutViewController.h"
#import "ListViewController.h"
#import "BookmarkViewController.h"
#import "LocationViewController.h"

//
//  Customize NavigationBar
//  - change background of navigation bar
//  - set green color for back button
//
@implementation UINavigationBar (CustomNaviBar)

- (void)drawRect:(CGRect)rect
{
    UIImage *image = [UIImage imageNamed:BGNavigation];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    [self setTintColor:[UIColor colorWithRed:53.0f/255.0f green:91.0f/255.0f blue:0.0f alpha:1.0f]];
}
@end

@implementation MainViewController

@synthesize weather;
@synthesize search;
@synthesize locationGotCha;
@synthesize alertGPS;
@synthesize alertUpdateLocation;
@synthesize arrDisplay;
@synthesize arrAllCateNames;
@synthesize arrButton;
@synthesize dictDisplay;
@synthesize buttonOne;
@synthesize buttonTwo;
@synthesize buttonThree;
@synthesize buttonFour;
@synthesize buttonFive;
@synthesize buttonSix;
@synthesize buttonSeven;
@synthesize buttonEight;
@synthesize buttonTemp;
@synthesize imageRecycle;
@synthesize category;
@synthesize arrCateNameDisplayed;
@synthesize arrDataAlertView;

static CLLocation *lastKnownLocation = nil;

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];    
    // Release any cached data, images, etc that aren't in use.
}

+ (CLLocation *)getLocation
{
    return lastKnownLocation;
}

+ (void)setLocation:(CLLocation *)location
{
    lastKnownLocation = [location retain];
}

#pragma mark - View lifecycle

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 */

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES];
    
    if(lastKnownLocation != nil)
    {
        weather.latitude = lastKnownLocation.coordinate.latitude;
        weather.longitude = lastKnownLocation.coordinate.longitude;
        [weather getWeather];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    // Set Hidden Navigation Bar
    [self.navigationController setNavigationBarHidden:NO];
    
    // Hidden Cancel button and set text search is nil
    [search resignFirstResponder];
    search.text = @"";
    search.showsCancelButton = NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if(weather == nil) {
        weather = [[WeatherInfoViewController alloc] init];
          
    }
    [self.view addSubview:weather.view];
    
    alertGPS = [[UIAlertView alloc] initWithTitle:@"Getting Location..." message:@" " delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    UIActivityIndicatorView *progress= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
    progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    [alertGPS addSubview:progress];
    [progress startAnimating];
    [progress release];
    
    [alertGPS show];
    
    locationGotCha = [[LocationGotcha alloc] init];
    locationGotCha.delegate = self;
    [locationGotCha startUpdates];
    
    //[DBManager removeDB];
    //check exists db, if it isn't exists,create db
    if(![DBManager checkExists])
        [DBManager createDB];
    
    // Load Setting
    [Settings loadSettings];
    
    // Load Background image
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:BGHome]]];
      
    // Transperance SearchBar Background
    [[[search subviews] objectAtIndex:0] removeFromSuperview];
    search.delegate = self;
    search.tintColor = [UIColor colorWithRed:53.0f/255.0f green:91.0f/255.0f blue:0.0f alpha:1.0f]; 
    
    // Load init display
    [self initDisplay];
}


- (void)viewDidUnload
{
    self.weather = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.buttonOne = nil;
    self.buttonTwo = nil;
    self.buttonThree = nil;
    self.buttonFour = nil;
    self.buttonFive = nil;
    self.buttonSix = nil;
    self.buttonFive = nil;
    self.buttonSix = nil;
    self.buttonSeven = nil;
    self.buttonEight = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc
{
    [category release];
    [weather release];
    [locationGotCha release];
    [alertGPS release];
    [alertUpdateLocation release];
    [buttonOne release];
    [buttonTwo release];
    [buttonThree release];
    [buttonFour release];
    [buttonFive release];
    [buttonSix release];
    [buttonSeven release];
    [buttonEight release];
    [super dealloc];
}

- (void)newPhysicalLocation:(CLLocation *)location
{
    //[self.view addSubview:weather.view];
    lastKnownLocation = [location retain];
    weather.latitude = lastKnownLocation.coordinate.latitude;
    weather.longitude = lastKnownLocation.coordinate.longitude;
    [weather getWeather];      
    
    [alertGPS dismissWithClickedButtonIndex:0 animated:YES];
}

//
//  Handler Button Tapped
//
//
- (IBAction)buttonTapped:(id)sender {
    UIButton *button = (UIButton*)sender;
    UIViewController *viewController = nil;
    
    switch (button.tag) {
        case 1: 
            // Push Category View to Navigation Controller
            viewController = [[CategoryViewController alloc] init];
            break;
        /*
        case 2: 
            // Push Search View to Navigation Controller
            viewController = [[SearchViewController alloc] init];
            break;
        */
        case 3: 
            // Push Setting View to Navigation Controller
            viewController = [[SettingsViewController alloc] init];
            break;
        
        case 4: 
            // Push About Me View to Navigation Controller
            viewController = [[AboutViewController alloc] init];
            break;        
            
        default:
            break;
    }
    [self pushViewController:viewController];    
    [viewController release];
}

//
//  getAllCateNamesWith
//  - Get all categories name from DB
//  
//
- (NSMutableArray *)getAllCateNamesWith:(Category *)cat
{
    NSMutableArray *muArray = [[[NSMutableArray alloc] init] autorelease];
    for (int i=0; i < [cat.list count]; i++) {
        Category *temp = [cat.list objectAtIndex:i];
        [muArray addObject:temp.CategoryName];
    }
    return muArray;
}

// 
//  init to display
//  
//  
// 
- (void)initDisplay
{
    NSLog(@"initDisplay Function Loading...");
    
    // Init 8 button
    NSArray *tempButton = [[NSArray alloc] initWithObjects:buttonOne, buttonTwo, buttonThree, buttonFour, buttonFive, buttonSix, buttonSeven, buttonEight, nil];
    self.arrButton = tempButton;
    [tempButton release];
    
    // Get all cateogory names from DB and save to arrAllCateNames variable
    if (category == nil) {
        category = [[Category alloc] init];
    }
    [category getAllCategories];
    self.arrAllCateNames = [self getAllCateNamesWith:category];
    
    // Get array display from pList file to display and save to arrayDisplay variable
    [self getArrCateIDDisplay];
     
    // Approve arrayDisplay variable to setBackground for UIButton
    for (int i = 0; i < [self.arrDisplay count]; i++) {
        int cateID = [[self.arrDisplay objectAtIndex:i] intValue];
        UIButton *button = [self.arrButton objectAtIndex:i];
        if (cateID == 0) {
            [self setButtonBG:button withBackground:BGAdd];
        }
        else {
            [self setButtonBG:button withBackground:[self getCateNameFrom:cateID]];
        }
    }
}

//
//  GetArrCateIDDisplay
//  
//  get array display from plist file and save to arrDisplay variable
// 
- (void)getArrCateIDDisplay
{
    // Get dictionary from plist file
    [Display loadDisplay];
    self.dictDisplay = [Display getAllDisplay];
    
    // Get array id category from dictionay
    NSArray *temp = [[self.dictDisplay allKeys] sortedArrayUsingSelector:@selector(compare:)];
    [self.arrDisplay removeAllObjects];
    
    NSMutableArray *muArrTemp = [[NSMutableArray alloc] init];
    for (int i=0; i < [temp count]; i++) {
        NSString *key = [temp objectAtIndex:i];
        NSString *value = [self.dictDisplay objectForKey:key];
        [muArrTemp addObject:value];
    }
    self.arrDisplay = muArrTemp;
    [muArrTemp release];
}

//
//  setButtonBG
//
// 
- (void)setButtonBG:(UIButton *)button withBackground:(NSString *)nameBG
{
    [button setBackgroundImage:[UIImage imageNamed:nameBG] forState:UIControlStateNormal];
}

//
//  getCateNameFrom:cateID
//
//
- (NSString *)getCateNameFrom:(int)cateID
{
    NSString *cateName = @"";
    for (int i=0; i < [category.list count]; i++) {
        Category *temp = [category.list objectAtIndex:i];
        if (temp.CategoryID == cateID) {
            cateName = temp.CategoryName;
            break;
        }
    }
    return cateName;
}


/*
 func: UpdateCategoryNameDisplay
 */
- (NSMutableArray *)getArrCateNameDisplayedFrom:(NSArray *)arrayDisplay
{
    NSMutableArray *temp = [[[NSMutableArray alloc] init] autorelease];
    for (NSString *item in arrayDisplay) {
        int cateID = [item intValue];
        if (cateID != 0) {
            [temp addObject:[self getCateNameFrom:cateID]];
        } 
    }
    return temp;
}

//
//  touches Began
//
//
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    NSLog(@"touchesBegan is load");
    [self getArrCateIDDisplay];
    
    for (UITouch *touch in touches) {
        // Check whether button tap
        for (int i = 0; i < [self.arrButton count]; i++) {
            CGRect frame = [[self.arrButton objectAtIndex:i] frame];
            if (CGRectContainsPoint(frame, [touch locationInView:self.view])) {
                indexButtonTouch = i;
                category_ID = [[self.arrDisplay objectAtIndex:indexButtonTouch] intValue];
                category_Name = [self getCateNameFrom:category_ID];
                // Create a temp button with frame at button tapped and assign to buttonTemp variable.
                if ( category_ID != 0) {
                    UIButton *newButton = [[UIButton alloc] init];
                    newButton.frame = frame;
                    [self.view addSubview:newButton];
                    buttonTemp = newButton;
                    [newButton release];
                }
                break;
            }
            else {
                indexButtonTouch = -1;
            }
        }
    }
    // Assign canMove variable to FALSE
    canMove = FALSE;
}

//
//  touches Moved
//
//
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"touchesMoved is load");
    
    canMove = TRUE;
    
    // Set BG of Button temp to move
    //int cateID = [[self.arrDisplay objectAtIndex:indexButtonTouch] intValue];
    //NSString *cateName = [self getCateNameFrom:cateID];
    if (category_ID !=0) {
        [self setButtonBG:buttonTemp withBackground:category_Name];
        
        // Set new location for button temp
        for (UITouch *touch in touches) {
            if (CGRectContainsPoint([buttonTemp frame], [touch locationInView:self.view])) {
                buttonTemp.center = [touch locationInView:self.view];
            }
        }
        [self setButtonBG:[self.arrButton objectAtIndex:indexButtonTouch] withBackground:BGAdd];

    }
}

//
// touch Ended
//
//
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"touchesEnded is load");
    
    if (indexButtonTouch == -1) {
        NSLog(@"index Button Touch == -1");
        return;
    }
    else {
        //int cateID = [[self.arrDisplay objectAtIndex:indexButtonTouch] intValue]; 
        if (category_ID == 0) {
            NSLog(@"Add Category Function");
            [self addCategory];
        }
        // cateID !=0
        else {
            if (canMove) {
                for (UITouch *touch in touches) {
                    // touch in recycle bin
                    if (CGRectContainsPoint([imageRecycle frame], [touch locationInView:self.view])) {
                        NSLog(@"Move Button Function");
                        [self removeCategory];
                    }
                    // touch out recycle bin
                    else {
                        [buttonTemp removeFromSuperview];
                        [self setButtonBG:[self.arrButton objectAtIndex:indexButtonTouch] withBackground:category_Name];
                    }
                }
                category_ID = 0;
            }
            else {
                [buttonTemp removeFromSuperview];
                [self openCategory];
            }
        }
    }
}


/*
 func: getCategoryID
 desc:
 to do plist:
 */
- (int)getCategoryID:(NSString *)categoryName
{
    int cateID = 0;
    for (int i=0; i < [category.list count]; i++) {
        Category *temp = [category.list objectAtIndex:i];
        if (temp.CategoryName == categoryName) {
            cateID = temp.CategoryID;
            break;
        }
    }
    return cateID;
}
/*
 func: AddCategoryToHomeScreen
 desc:
 to do list:
 
 */
- (void)addCategory
{
    // Get all category name had display
    [self.arrCateNameDisplayed removeAllObjects];
    //[self getArrCateIDDisplay];
    self.arrCateNameDisplayed = [self getArrCateNameDisplayedFrom:self.arrDisplay];
    
    NSMutableArray *dataAlertView = [[NSMutableArray alloc] init];
    [dataAlertView removeAllObjects];
    
    // add array all category name to data alert view
    [dataAlertView addObjectsFromArray:self.arrAllCateNames];
    // remove category displayed from all catgory name
    [dataAlertView removeObjectsInArray:self.arrCateNameDisplayed];
    
    [self.arrDataAlertView removeAllObjects];
    self.arrDataAlertView = dataAlertView;
    
    [[[[CustomAlertViewController alloc] initWithCaller:self data:self.arrDataAlertView  images:self.arrDataAlertView title:@"Please, select a category" andContext:nil] autorelease] show];
    
    [dataAlertView release];
}

/*
 func: didSelectRowAtIndex
 desc: 
 to do list:
 */
- (void)didSelectRowAtIndex:(NSInteger)row withContext:(id)context 
{    
    if (row != -1) {
        // Update CategoryID at location of button.
        NSArray *temp = [[dictDisplay allKeys] sortedArrayUsingSelector:@selector(compare:)];
        
        NSString *key = [temp objectAtIndex:indexButtonTouch];
        NSString *cateName = [self.arrDataAlertView objectAtIndex:row];
        NSString *cateID = [NSString stringWithFormat:@"%d",[self getCategoryID:cateName]];
        NSLog(@"Key %@ and value: %@", key, cateID);
        
        // Update plist file
        [Display updateDisplay:key andValue:cateID];
        
        // Set BG Button Add
        [self setButtonBG:[self.arrButton objectAtIndex:indexButtonTouch] withBackground:cateName];
        
        // Update arrDisplay variable
        //[self getArrCateIDDisplay];
        
    }
}

//
//  remove Category from main screen
//
//
- (void)removeCategory
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Deleted" message:[NSString stringWithFormat:@"Do you want to delete this %@?",category_Name] delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
                          
    [alert show];
    [alert release];
}

//
//  alertView action of remove category
//
//
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == [alertView cancelButtonIndex] && alertView == alertGPS)
    {
        [locationGotCha stopUpdates];
        
        if(lastKnownLocation == nil)
        {
            if(alertUpdateLocation != nil)
                [alertUpdateLocation release];
            alertUpdateLocation = [[UIAlertView alloc] initWithTitle:@"" message:@"Do you want to update location by manual ?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
            [alertUpdateLocation show];
        }
        
        return;
    }    
    else if(alertView == alertUpdateLocation)
    {
        if(buttonIndex == 1)
        {
            LocationViewController *locationViewController = [[LocationViewController alloc] init];
            [self pushViewController:locationViewController];
            //[self.navigationController pushViewController:locationViewController animated:YES];
            [locationViewController release];
        }
        return;
    }
    else 
    {
        UIButton *button = [self.arrButton objectAtIndex:indexButtonTouch];
        //int cateID = [[self.arrDisplay objectAtIndex:indexButtonTouch] intValue];
        //NSString *cateName = [self getCateNameFrom:cateID];
        
        if (buttonIndex == 1) {
            // Remove this category
            NSLog(@"Yes button clicked");
            [buttonTemp removeFromSuperview];
            
            // Update arrDisplay
            // Get key updated
            NSArray *temp = [[dictDisplay allKeys] sortedArrayUsingSelector:@selector(compare:)];
            NSString *key = [temp objectAtIndex:indexButtonTouch];
            
            // Update value and key to plist
            [Display updateDisplay:key andValue:@"0"];
            
            // Set BG Button to BGAdd
            [self setButtonBG:button withBackground:BGAdd];
            
            // Update arrDisplay variable
            //[self getArrCateIDDisplay];
        }
        else {
            NSLog(@"Cancel button clicked");
            [buttonTemp removeFromSuperview];
            
            [self setButtonBG:button withBackground:category_Name]; 
            return;
        }
    }
    
}
/*
 func: OpenCategoryAtHomeScreen
 desc:
 to do list:
 */
- (void)openCategory
{
    Category *temp = nil;
    for (int i = 0; i < [category.list count]; i++) {
        Category *cat = [category.list objectAtIndex:i];
        
        if (cat.CategoryName == category_Name) {
            temp = cat;
            break;
        }
    }
    
    if([temp.CategoryName isEqualToString:@"Favorite"])
    {
        BookmarkViewController *bookmarkViewControoler = [[BookmarkViewController alloc] init];
        [self pushViewController:bookmarkViewControoler];
        //[self.navigationController pushViewController:bookmarkViewControoler animated:YES];
        [bookmarkViewControoler release];
    }
    else
    {
        ListViewController *listViewController = [[ListViewController alloc] initWithCategory:temp andKey:@""];
        [self pushViewController:listViewController];
        //[self.navigationController pushViewController:listViewController animated:YES];
        [listViewController release];
    }     
}

/*
 func: PushViewController   
 desc: push a view controller to stack of navigation controller
 to do list: 
 */
- (void)pushViewController:(UIViewController*)viewController
{
    [UIView beginAnimations:@"Animation" context:nil];
    [UIView setAnimationDuration:1.0];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [self.navigationController pushViewController:viewController animated:NO];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.navigationController.view cache:NO];
    [UIView commitAnimations];
}


/*
 Search Bar
 */
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:YES animated:YES];
    
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    search.text = @"";
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"Search Button Tapped");
    ListViewController *list = [[ListViewController alloc] initWithCategory:nil andKey:search.text];
    [self pushViewController:list];
    [list release];
}
@end
